<script setup lang="ts">
import type { Field } from '/@/components/Render/type';
import { labels } from '/@/api/admin/metaField';
import { saveCondition } from '/@/api/admin/metaEntity';

import { watch } from 'vue';

const AdvancedFilter = defineAsyncComponent(() => import('/@/components/AdvancedFilter/index.vue'));
const initialFormFields = ref<Field[]>([]);
const visible = ref(false);
const fields = ref<Field[]>([]);
const conditions = ref();
let currentId = '';
const tableName = ref();
const selectedFiled = ref([]);
const advancedFilterRef = ref();
const emit = defineEmits(['refresh']);
// 打开弹窗
const openDialog = (id: string, conditionData: object, label: string) => {
	tableName.value = label;
	currentId = id;
	if (conditionData && conditionData.length > 0) {
		conditions.value = JSON.parse(JSON.stringify(conditionData[0]));
	} else {
		conditions.value = {
			conditions: [],
			groups: [],
			operator: 'and',
		};
	}
	fields.value = [];
	visible.value = true;
	labels(id).then((res) => {
		res.data.forEach((item) => {
			fields.value.push({
				id: item.label,
				label: item.name,
			});
		});
	});
};
const save = () => {
	visible.value = false;
	removeCondition(conditions.value);
	saveCondition(currentId, conditions.value).then((res) => {
		emit('refresh');
	});
};

const removeCondition = (groups) => {
	if (groups.conditions === undefined) {
		return;
	}
	groups.conditions = groups.conditions.filter((item) => {
		return item.field;
	});

	let flag = true;
	groups.groups.forEach((item) => {
		removeCondition(item);
		if (item.conditions.length != 0){
			flag = false;
		}
	});
	if (flag) {
		groups.groups = []
	}

};

watch(
	conditions,
	(newValue, oldValue) => {
		selectedFiled.value = [];
		setSelectedFiled(newValue);
	},
	{
		deep: true,
	}
);
const setSelectedFiled = (groups) => {
	if (groups.conditions === undefined) {
		return;
	}

	groups.conditions.forEach((item) => {
		selectedFiled.value.push(item.field);
	});
	groups.groups.forEach((item) => {
		setSelectedFiled(item);
	});
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<template>
	<el-dialog title="列表搜索设置" v-model="visible" :draggable="true">
		<advanced-filter ref="advancedFilterRef" :selectedFiled="selectedFiled" v-model="conditions" :filter-fields="[...initialFormFields, ...fields]" />
		<template #footer>
			<el-button type="primary" @click="save"> 确认</el-button>
		</template>
	</el-dialog>
</template>

<style scoped lang="scss"></style>
